import * as step from '@flow-step/step-toolkit'
import * as fs from 'fs-extra'
import path from 'path'


export function copyDiffFiles(diffListPath: string, sourceDir: string, targetDir: string, subDirectory?: string|undefined) {
    const diffList = fs.readFileSync(diffListPath, 'utf-8').trim()
    step.debug(`diffList: ${diffList}`)
    if (diffList === '') {
        step.info('Diff list is empty. No Java file changes found')
    } else {
        step.info('Files to scan:')
        const files = diffList.trim().split(' ')
        step.debug(`files: ${files}`)
        for (const file of files) {
            let trimmedFile = file.trim()
            if (subDirectory){
                trimmedFile = path.relative(subDirectory, trimmedFile)
            }
            const filePath = path.join(sourceDir, trimmedFile)
            step.debug(`filePath: ${filePath}`)
            if (fs.existsSync(filePath)) {
                step.info(filePath)
                const relativePath = path.dirname(trimmedFile)
                const destDir = path.join(targetDir, relativePath)
                if (!fs.existsSync(destDir)) {
                    fs.mkdirSync(destDir, {recursive: true})
                }
                fs.copyFileSync(filePath, path.join(targetDir, trimmedFile))
            }
        }
    }
}

